﻿using System;
using System.IO;
using System.Collections.Generic;

namespace test3
{
  class test_3
  {
    // 存取key value
    public void Dictionary()
    {
      // 创建泛型哈希表
      Dictionary<int, string> myDictionary = new Dictionary<int, string>();
      myDictionary.Add(1, "C#");
      myDictionary.Add(2, "C++");
      myDictionary.Add(3, "java");
      myDictionary.Add(4, "js");

      // 判断是否存在
      if (myDictionary.ContainsKey(1))
      {
        Console.WriteLine("myDictionary 1：" + myDictionary[1]);
      }
      //2.删除元素
      myDictionary.Remove(3);
      //4.显示容量和元素个数
      Console.WriteLine("元素个数：{0}", myDictionary.Count);

      //3.0以上版本
      foreach (var item in myDictionary)
      {
        Console.WriteLine(item.Key + "," + item.Value);
      }
      //6.通过KeyValuePair遍历元素
      foreach (KeyValuePair<int, string> kvp in myDictionary)
      {
        Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);

      }
      //7.得到哈希表键的集合
      Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys;
      //遍历键的集合
      foreach (int n in keyCol)
      {
        Console.WriteLine("key={0}", n);
      }
      //8.得到哈希表值的集合
      Dictionary<int, string>.ValueCollection valCol = myDictionary.Values;
      //遍历值的集合
      foreach (string s in valCol)
      {
        Console.WriteLine("value：{0}", s);
      }


      // 9.使用TryGetValue方法获取指定键对应的值
      string slove = string.Empty;
      if (myDictionary.TryGetValue(20, out slove))
      {
        Console.WriteLine("查找结果：{0}", slove);
      }

      Console.WriteLine("查找结果111：{0}", myDictionary.TryGetValue(20, out slove));
      Console.WriteLine("value：{0}", myDictionary.ContainsKey(11));




    }
  }
}
